package cn.servlet;


import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.dto.Message;
import cn.dto.Result;
import cn.dto.common;
import cn.pojo.Login;
import cn.service.impl.LoginServiceImpl;
import cn.service.LoginService;


/**
 * 处理登录请求
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private LoginService userService = new LoginServiceImpl();
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String postdata = common.getPostData(request.getInputStream(), request.getContentLength(), null);
		JSONObject loginparam = JSON.parseObject(postdata);
		String email = loginparam.getString("email"); 
		String password = loginparam.getString("password");
		System.out.println("数据"+email+password);
		try {
			Login userData = userService.getUserByEmailAndPassword(email, password);
			System.out.println("数据2"+userData);
			Result result = new Result();
			if(userData!=null) {
				//登录成功
				Message message = new Message(200,"登录成功");
				Login user = new Login();
				user.setEmail(userData.getEmail());
				user.setNickname(userData.getNickname());
				user.setRole(userData.getRole());
				user.setStatus(userData.getStatus());
				result.setData(user);
				result.setMessage(message);
				
			}else {
				//登录失败
				Message message = new Message(400,"用户名或密码错误");
				result.setMessage(message);
			}
			response.getWriter().write(JSON.toJSONString(result));
		} catch (ClassNotFoundException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
